package com.cncbox.controller;

import com.cncbox.common.Utils;
import com.cncbox.entity.NoteResult;
import com.cncbox.entity.Resource;
import com.cncbox.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Date;

/**
 * 资源Controller
 * Created by songs on 2016/4/7.
 */
@Controller
@RequestMapping(value = "/manager")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;
    private String imagePath;

    //添加资源
    @RequestMapping(value = "/addResource")
    public String addResource(@RequestParam MultipartFile resourceFile, HttpServletRequest httpServletRequest, Resource resource) throws Exception {
        Integer artId = resource.getArtId();
        String note = "";
        if (artId != null && 0 < artId && 0 < resourceFile.getSize()) {

            //获取文件后缀名
            String suffix = resourceFile.getOriginalFilename().substring(resourceFile.getOriginalFilename().lastIndexOf("."));

            //处理上传文件名（时间）+后缀
            String fileName = Utils.notSymbol(new Date()) + suffix;

            //设置上传文件路径
            resource.setPathName(fileName);

            //添加上传时间
            resource.setAddTime(Utils.format(new Date()));

            //类型全部给图片
            resource.setType('1');

            //设置存储目录
            String imagePath = httpServletRequest.getSession().getServletContext().getRealPath("resource/image");

            //进行数据添加
            NoteResult noteResult = resourceService.addResource(resource);
            if (0 < noteResult.getStatus()) {
                //进行写入文件
                Utils.inputFile(resourceFile, imagePath, fileName);
                note = "添加成功";
            } else {
                note = "添加失败";
            }
        } else {
            note = "参数错误";
        }
        httpServletRequest.setAttribute("message", note);
        return "redirect:/manager/jump.html";
    }


    //查询资源，根据Id
    @RequestMapping(value = "/queryResource")
    @ResponseBody
    public NoteResult queryResource(Integer resourceId) throws Exception {
        NoteResult noteResult = new NoteResult();
        //判断传入参数是否正确
        if (resourceId != null && 0 < resourceId) {
            noteResult = resourceService.queryResource(resourceId);
        } else {
            noteResult.setStatus(0);
            noteResult.setMsg("PARAMETER_ERROR");
        }
        return noteResult;
    }

    //修改资源
    @RequestMapping(value = "/updateResource")
    public String updateResource(@RequestParam MultipartFile resourceFile, HttpServletRequest httpServletRequest, Resource resource) throws Exception {
        NoteResult noteResult = new NoteResult();
        String imagePath = "";
        String fileName = "";
        if (0 < resourceFile.getSize()) {
            //获取文件后缀名
            String suffix = resourceFile.getOriginalFilename().substring(resourceFile.getOriginalFilename().lastIndexOf("."));

            //处理上传文件名（时间）+后缀
            fileName = Utils.notSymbol(new Date()) + suffix;

            //设置上传文件路径
            resource.setPathName(fileName);

            //设置存储目录
            imagePath = httpServletRequest.getSession().getServletContext().getRealPath("resource/image");
        }
        if (resource != null) {
            noteResult = resourceService.updateResource(resource);
            if (0 < noteResult.getStatus() && 0 < resourceFile.getSize()) {
                Utils.inputFile(resourceFile, imagePath, fileName);
            }
        } else {
            noteResult.setStatus(0);
            noteResult.setMsg("PARAMETER_ERROR");
        }
        httpServletRequest.setAttribute("message", noteResult);
        return "redirect:/manager/jump.html";
    }

    //删除资源
    @RequestMapping(value = "/removeResource")
    public String removeResource(HttpServletRequest httpServletRequest, Integer resourceId) throws Exception {
        NoteResult noteResult = new NoteResult();
        if (resourceId != null && 0 < resourceId) {
            noteResult = resourceService.removeResource(resourceId);
        } else {
            noteResult.setStatus(0);
            noteResult.setMsg("PARAMETER_ERROR");
        }
        return "redirect:/manager/jump.html";
    }

    //文章上传资源
    @RequestMapping(value = "/updateFile")
    public void uploadFile(@RequestParam MultipartFile upload, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest, Integer CKEditorFuncNum) throws Exception {

        httpServletResponse.setCharacterEncoding("utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        //获取文件后缀名
        String suffix = upload.getOriginalFilename().substring(upload.getOriginalFilename().lastIndexOf("."));
        //处理上传文件名（时间）+后缀
        String fileName = Utils.notSymbol(new Date()) + suffix;

        String imagePath = httpServletRequest.getSession().getServletContext().getRealPath("resource/image/content");

        Utils.inputFile(upload, imagePath, fileName);

        // 返回"图像"选项卡并显示图片  request.getContextPath()为web项目名
        out.println("<script type=\"text/javascript\">");
        out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
                + ",'" + httpServletRequest.getContextPath() + "/resource/image/content/" + fileName + "','')");
        out.println("</script>");

    }
    ;


}
